import {useProductId} from '@/hooks/useProductId'
import styled from './index.module.scss'
import {useCallback, useEffect, useMemo, useRef, useState} from 'react'
import Token from '@/component/Token'
import {homeComment, product, shoppingOrder, shoppingSave} from '@/api'
import {productColor, ProductInfoComment, productType} from '@/type/homeType'
import config from '@/static/config'
import {Button, Input, List, message, Space} from 'antd'
import {MinusOutlined, PlusOutlined} from '@ant-design/icons'
import {productSaveTypeRecoilState} from '@/store/productInfoStore'
import {useRecoilState} from 'recoil'
import {InputRefType} from '@/type/antd'
import {ShoppingList} from '@/type/shopping'
import {info} from '@/utils'
import {useNavigate} from 'react-router-dom'
import dayjs from 'dayjs'

const users = info()!


type productInfoInfo = [string, string]


const tabs = [
	{
		label: '商品详情',
		key: 0
	},
	{
		label: '商品评价',
		key: 1
	}
]

const ProductInfoFooter = (props: {
	pic: string[]
	info: productInfoInfo[]
	product_id: string
}) => {
	const [active, setActive] = useState(0)
	const [list, setList] = useState([])


	useEffect(() => {
		console.log(props.product_id)
		homeComment({
			product_id: props.product_id
		}).then(res => {
			setList(res.data)
			setList(res.data)
		})
	}, [])


	const divFun = (item:ProductInfoComment) => (
		<div className={styled.comment_list}>
			<span>{item.username}</span>
			<span>{dayjs(item.comment_create_time).format("YYYY-MM-DD HH:mm:ss")}</span>
		</div>
	)

	const productDOM = useMemo(() => {
		if (active === 0) {
			return (
				<div>
					<div className={styled.footer_info}>
						{
							props.info && props.info.map((item, i) => (
								<div key={i}>
									<span>{item.join('：')}</span>
								</div>
							))
						}
					</div>
					<div className={styled.footer_pics}>
						{
							props.pic && props.pic.map((item, i) => (
								<img width={'90%'} src={config.productImgUrl + item} key={i} alt=""/>
							))
						}
					</div>
				</div>
			)
		}
		if (active === 1) {
			return (
				<div className={styled.comment}>
					<List
						bordered={false}
						dataSource={list}
						pagination={false}
						itemLayout={"horizontal"}
						renderItem={(item:ProductInfoComment) => (
							<List.Item>
								<List.Item.Meta
									title={divFun(item)}
									description={item.remark}
								/>
							</List.Item>
						)}
					></List>
				</div>
			)
		}
	}, [active, props, list])

	return (
		<div className={styled.footer}>
			<div className={styled.tabs}>
				{
					tabs.map(item => (
						<h3
							key={item.key}
							className={`${active === item.key && styled.tabs_active}`}
							onClick={() => setActive(item.key)}
						>{item.label}</h3>
					))
				}
			</div>
			{productDOM}
		</div>
	)
}

const ProductInfo = () => {
	const navigate = useNavigate()
	const product_id = useProductId()
	const [save, setSave] = useRecoilState(productSaveTypeRecoilState)
	const [info, setInfo] = useState<productType>()
	const [pic, setPic] = useState<string>('')

	const input = useRef<InputRefType| null >(null)

	useEffect(() => {
		if (product_id.length) {
			product({
				product_id
			}).then(res => {
				if (res.code === 200) {
					setInfo(res.data)
					setPic(res.data.product.product_pic)
					if (res.data.color.length){
						setSave({
							num: 1,
							colorId: res.data.color[0].id
						})
					}else {
						setSave({
							num: 1,
							colorId: null
						})
					}

				}
			})
		}
	}, [product_id])

	const imgClick = useCallback((item: string) => {
		setPic(() => item)
	}, [pic])
	// 颜色的点击事件
	const colorClick = useCallback((item: productColor) => {
		imgClick(item.product_color_pic)
		const obj = {
			num: save.num,
			colorId: item.id
		}
		setSave(obj)
	}, [save])
	// 加
	const onPlus = useCallback(() => {
		const value = Number(input.current!.input?.value)
		setSave({
			colorId: save.colorId,
			num: value + 1
		})
	}, [save])
	// 减
	const onMinus = useCallback(() => {
		if (save.num) {
			const value = Number( input.current!.input?.value )
			setSave( {
				colorId: save.colorId,
				num: value - 1
			} )
		}
	}, [save])

	const inputChange = useCallback((e:{
		target: HTMLInputElement
		currentTarget: HTMLInputElement
	}) => {
		const value = e.target.value
		const regexp:RegExp = /[^\d]/g
		const obj = {
			num: 0,
			colorId: save.colorId
		}
		if (regexp.test( value )) {
			obj.num = 1
		}else {
			obj.num = Number(value.trim())
		}
		// 修改num的时候可能会出现nan的情况
		if (isNaN(obj.num)) {
			obj.num = 1
		}
		setSave(obj)
	}, [])

	//  添加购物车
	const shopping = useCallback(() => {
		const obj = {
			num: save.num,
			colorId: save.colorId
		}

		if (!obj.colorId) {
			obj.colorId = info!.color[0].id
		}

		shoppingSave({
			num: obj.num,
			colorId: obj.colorId!,
			product_id
		}).then(res => {
			if (res.code === 200) {
				message.success(res.message)
			}
		})
	}, [product_id, info])

	// 立即购买
	const purchase = useCallback(() => {
		const obj:ShoppingList = {
			brand_id: info!.product.brand_id!,
			cart_lose: 1,
			cart_money: info!.product.product_money!,
			cart_num: save.num,
			category_id: info!.product.category_id!,
			color_id: save.colorId || info!.color[0].id,
			product_id: product_id,
			product_name: info!.product.product_name!,
			product_pic: info!.product.product_pic!,
			user_id: users.id || 0,
			id:  0,
			discount: info!.product.discount
		}
		shoppingOrder([obj]).then(res => {
			if (res.code === 200) {
				navigate('/home/settle', {
					replace: true
				})
			}
		})
	}, [product_id, info, save])

	const footer = useMemo(() => {
		if (product_id.length) {
			return <ProductInfoFooter
				pic={info?.info.pic}
				info={info?.info.info}
				product_id={product_id}
			/>
		}
		return ''
	}, [product_id, info])

	return (
		<Token>
			<div className={styled.info}>
				{/*<h2>{info?.product.product_name}</h2>*/}
				<div className={styled.header}>
					{/*轮播图*/}
					<div>
						<div className={styled.imgs}>
							<img
								src={config.productImgUrl + pic}
								alt={''}
							/>
						</div>
						<div className={styled.pics}>
							{
								info?.pic.map((item, i) => (
									<img
										src={config.productImgUrl + item}
										width={90}
										key={i}
										onMouseEnter={() => imgClick(item)}
										height={100}
										alt={''}
									/>
								))
							}
						</div>
					</div>
					{/*商品信息*/}
					<div className={''}>
						<h3 style={{
							marginTop: '30px'
						}}>{info?.product.product_name}</h3>
						<div className={styled.order}>已售 <span>{info?.product.product_order}</span></div>
						<p className={ info?.product.discount !== 0 && styled.discount}>&yen;{info?.product.product_money.toFixed(2)}</p>
						{
							info?.product.discount !== 0 && (<p>&yen;{info?.product.discount.toFixed(2)}</p>)
						}
						<div className={styled.color}>
							<span>类型：</span>
							<div>
								{
									info?.color.map((item, i) => {
										if (item.product_color_count === 0) {
											return (
												<div key={i} className={styled.color_not}>
													<img src={config.productImgUrl + item.product_color_pic} width={30} height={30} alt=""/>
													<span style={{marginLeft: '6px'}}>{item.product_color_name}</span>
												</div>
											)
										}
										return (
											<div className={`${(save.colorId === item.id) && styled.color_active}`} key={i} onClick={() => colorClick(item)}>
												<img src={config.productImgUrl + item.product_color_pic} width={30} height={30} alt=""/>
												<span style={{marginLeft: '6px'}}>{item.product_color_name}</span>
											</div>
										)
									})
								}
							</div>
						</div>
						<div className={styled.num}>
							<span>数量</span>
							<div>
								<Button onClick={onMinus} size={'large'} disabled={save.num <= 1} icon={<MinusOutlined />}></Button>
								<Input
									size={'large'}
									style={{
										width: '100px'
									}}
									value={save.num}
									ref={input}
									onChange={inputChange}
								/>
								<Button onClick={onPlus} size={'large'} icon={<PlusOutlined />}></Button>
							</div>
						</div>
						<div className={styled.btns}>
							<Space>
								<Button
									disabled={info?.product.product_count === 0}
									classNames={styled.save}
									size={'large'}
									onClick={shopping}
								>加入购物车</Button>
								<Button
									size={'large'}
									onClick={purchase}
								>立即购买</Button>
							</Space>
						</div>
					</div>
				</div>
				{/*	商品参数及商品图片 */}
				{ footer }
			</div>
		</Token>
	)
}

export default ProductInfo

